package com.zkx.laolaiyi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zkx.laolaiyi.constant.*;
import com.zkx.laolaiyi.dto.UserDTO;
import com.zkx.laolaiyi.entity.LoginUser;
import com.zkx.laolaiyi.exceptions.UnknownException;
import com.zkx.laolaiyi.properties.PrivateKeyProperties;
import com.zkx.laolaiyi.result.Result;
import com.zkx.laolaiyi.service.LoginService;
import com.zkx.laolaiyi.utils.EncryptUtil;
import com.zkx.laolaiyi.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import javax.crypto.SecretKey;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 专门处理登录的Service
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final SecretKey secretKey;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<LoginUser> login(UserDTO userDTO) {
//        Authentication authenticationToken = UsernamePasswordAuthenticationToken
//                .unauthenticated(userDTO.getUsername(), userDTO.getPassword());
        Authentication authenticationToken = new AuthenticationTokenImpl(userDTO.getUsername(), userDTO.getPassword(), RoleTypeConstants.USER);
        Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (AuthenticationException e) {
            return Result.error(ResultCodeConstant.LOGIN_FAILED, ResultMsgConstant.LOGIN_FAILED);
        }
        Map<String, Object> claims = BeanUtil.beanToMap(userDTO);
        String token = JwtUtil.createJwt(secretKey, claims);
        String key = RedisConstants.USER_LOGIN_KEY + token;
            Long value = ((LoginUser) (authenticate.getPrincipal())).getUid();
            stringRedisTemplate.opsForValue().set(key, value.toString(), Duration.ofHours(RedisConstants.USER_LOGIN_TTL));
            return Result.success(token);
    }

    @Override
    public Result<String> logout() {
        return null;
    }
}
